package com.taotao.common.httpclient;

import org.apache.http.conn.HttpClientConnectionManager;

/**
 * 定期清理无效的连接的线程
 *
 */
public class IdleConnectionEvictor extends Thread {
	private final HttpClientConnectionManager connMgr;

	// 每隔多长时间,关闭无效连接
	private int time;
	private volatile boolean shutdown;

	public IdleConnectionEvictor(HttpClientConnectionManager connMgr, int time) {
		this.connMgr = connMgr;
		this.time = time;
		// 启动线程
		this.start();
	}

	// 定义线程任务,定时关闭失效的连接
	@Override
	public void run() {
		try {
			while (!shutdown) {
				synchronized (this) {
					// 每隔5秒钟一次
					wait(time);
					// 关闭失效的连接
					connMgr.closeExpiredConnections();
				}
			}
		} catch (InterruptedException ex) {
			// 结束
		}
		System.out.println("清理任务 即将结束。。");

	}

	public void shutdown() {
		shutdown = true;
		synchronized (this) {
			notifyAll();
		}
	}

}
